/* eslint-disable @typescript-eslint/indent */
import * as File from './file'
import { APIResult, success, fail } from './types'
import { Router } from 'express'

const router = Router()

router.get('/:lang/:filename/*', (req, res) => {
    // check
    const _ = req.params
    // console.log(_)
    const lang = (_.lang == '_') ? 'zh_CN' : _.lang
    if (!lang || !_.filename || !_[0])
        res.send(fail('Invalid arguments.'))
    else if (!File.ValidLangs.includes(lang))
        res.send(fail('No such language.'))
    else if (!File.ValidExcels.includes(_.filename))
        res.send(fail('No such excel file.'))
    else {
        const excel = File.getExcel(_.filename, lang)
        const xpath = _[0].split('/')
        // 中间结果
        // res.send({ success: true, value: { excel, xpath } })
        let x = excel
        try {
            xpath.forEach(key => {
                if (!isNaN(key))
                    x = x[parseInt(key)]
                else if (key == "keys")
                    x = Object.keys(x)
                else if (x.hasOwnProperty(key))
                    x = x[key]
                else
                    throw(`Invalid xpath: ${xpath}`)
            })
        } catch (e) {
            res.send(fail(`Error: ${e}`))
            return
        }
        res.send(success(x))
    }
})

export default router
